package com.z.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.z.common.configure.security.LoginUser;
import com.z.common.context.UserContext;
import com.z.common.exception.BusinessException;
import com.z.common.web.vo.request.PageVo;
import com.z.sys.entity.Dept;
import com.z.sys.entity.User;
import com.z.sys.mapper.DeptMapper;
import com.z.sys.mapper.UserMapper;
import com.z.sys.service.IDeptService;
import com.z.sys.vo.DeptExcelVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.*;

/**
 * 机构管理Service业务层处理
 *
 * @author z
 * @date 2022-11-07
 */
@Service
@Transactional
public class DeptServiceImpl extends ServiceImpl<DeptMapper,Dept> implements IDeptService {

    @Resource
    private DeptMapper deptMapper;
    @Resource
    private UserMapper userMapper;

    /**
     * 查询机构管理
     * @param dept 机构管理
     * @param pageVo
     * @return 机构管理 分页集合
     * */
    @Override
    public PageInfo<Dept> selectDeptPage(Dept dept, PageVo pageVo, String model) {
        PageHelper.startPage(pageVo.getPage(), pageVo.getLimit());
        List<Dept> data = selectDeptList(dept, model);

        return new PageInfo<>(data);
    }

    @Override
    public List<Dept> selectDeptList(Dept dept,String model) {
        if(StringUtils.isEmpty(model)){
            model = "人事";
        }
        List<Dept> data = null;
        int powerLevel = UserContext.getPowerLevel(model);
        if(powerLevel == 0){
            data = baseMapper.selectDeptList(dept);
        } else {
            QueryWrapper<Dept> queryWrapper = new QueryWrapper<Dept>().orderByAsc("code");
            if(dept.getParentId() != null){
                queryWrapper.like("parent_id", dept.getParentId());
            }
            if(StringUtils.isNotEmpty(dept.getNameAbbr())){
                queryWrapper.like("name_abbr", dept.getNameAbbr());
            }
            if(StringUtils.isNotEmpty(dept.getCode())){
                queryWrapper.like("code", dept.getCode());
            }
            List<Dept> list = getUnitListByRole("人事");
            if(null != list && list.size() > 0) {
                queryWrapper.and(e -> {
                    for (Dept d : list) {
                        e.eq("full_path", d.getFullPath()).or()
                        .likeRight("full_path", d.getFullPath()+"/").or();
                    }
                });

            }
            data = deptMapper.selectList(queryWrapper);
        }
        return data;
    }
    @Override
    public List<DeptExcelVo> selectDeptInfoList(Dept dept) {
        List<DeptExcelVo> data = null;
        int powerLevel = UserContext.getPowerLevel("人事");
        if(powerLevel != 0){
            QueryWrapper<DeptExcelVo> queryWrapper = new QueryWrapper<DeptExcelVo>();
            if(dept.getParentId() != null){
                queryWrapper.like("parent_id", dept.getParentId());
            }
            if(StringUtils.isNotEmpty(dept.getNameAbbr())){
                queryWrapper.like("name_abbr", dept.getNameAbbr());
            }
            if(StringUtils.isNotEmpty(dept.getCode())){
                queryWrapper.like("code", dept.getCode());
            }
            List<Dept> list = getUnitListByRole("人事");
            if(null != list && list.size() > 0) {
                queryWrapper.and(e -> {
                    for (Dept d : list) {
                        e.like("full_path", d.getFullPath()).or();
                    }
                });

            }
        }
        data = deptMapper.selectDeptInfoList(dept);

        return data;
    }

    @Override
    public boolean saveToDB(List<Dept> deptList) {
        boolean flag = saveBatch(deptList);
        List<Dept> deptDBList = list(new QueryWrapper<Dept>().eq("del", 0).eq("status", "1"));
        Map<String, Dept> codeDeptMap = new HashMap<>();
        for(Dept dept: deptDBList){
            codeDeptMap.put(dept.getCode(), dept);
        }
        deptList.forEach(data ->{
            data.setParentId(codeDeptMap.get(data.getFullPath()).getId());
            data.setFullPath("");
        });
        flag = updateBatchById(deptList);
        baseMapper.updateFullPath();
        return flag;
    }

    @Override
    public List<Dept> getUnitListByRole(String model) {

        LoginUser user = UserContext.getLoginUser();
        Set<String> roleNames = user.getRoleNames();
        if(user.getUserSn().equals("admin") || roleNames.contains("集团_"+model+"管理员")){
            return deptMapper.selectList(new QueryWrapper<Dept>().select("id,name_abbr,parent_id").notLike("code", "-").eq("del", 0).eq("status", "1").orderByAsc("code"));
        }else if (roleNames.contains("单位_"+model+"管理员")){
            return deptMapper.selectDeptByRoleName("单位_"+model+"管理员", user.getId());
        }else{
            return deptMapper.selectUnitByUserId(user.getId());
        }
    }

    @Override
    public List<Dept> getDeptListByRole() {
        int powerLevel = UserContext.getPowerLevel("考勤");
        String roleName = "";
        if(powerLevel == 0){
            return deptMapper.selectList(new QueryWrapper<Dept>().select("id,name_abbr,parent_id").eq("del", "0").orderByAsc("code"));
        } else if (powerLevel == 1){
            roleName = "单位_考勤管理员";
        } else if (powerLevel == 2 ){
            roleName = "科室_考勤负责人";
        } else if (powerLevel == 3 ){
            roleName = "班组_考勤负责人";
        } else {
            Dept db = deptMapper.selectOne(new QueryWrapper<Dept>().eq("id", UserContext.getLoginUser().getDeptId()));
            List<Dept> list = new ArrayList<Dept>();
            list.add(new Dept(db.getId(), db.getNameAbbr(), 0L));
            return list;
        }
        List<Dept> list = deptMapper.selectDeptByRoleName(roleName, UserContext.getLoginUser().getId());
        /*List<Dept> temp = new ArrayList<>();
        for(Dept dept : list){
            List<Dept> mList = deptMapper.selectList(new QueryWrapper<Dept>().select("id,name_abbr,parent_id").likeRight("full_path", dept.getFullPath()));
            if(mList != null && mList.size()>0){
                temp.addAll(mList);
            }
        }
        list.removeAll(temp);
        list.addAll(temp);*/
        return list;
    }

    @Override
    public boolean removeByIds(Collection list) {
        for(Object id : list){
            removeById((Serializable) id);
        }
        return true;
    }

    @Override
    public boolean removeById(Serializable id) {
        long count = userMapper.selectCount(new QueryWrapper<User>().eq("del", 0).eq("dept_id", id));
        if(count >= 1){
            throw new BusinessException("机构下存在人员，无法删除");
        }
        count = deptMapper.selectCount(new QueryWrapper<Dept>().eq("parent_id", id).eq("del", 0));
        if(count >= 1){
            throw new BusinessException("机构下存在子机构，无法删除");
        }
        Dept dept = deptMapper.selectById(id);
        dept.setDel(true);
        int r = deptMapper.updateById(dept);
        if(r > 0){
            return true;
        }
        return false;
    }
}
